/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PesquisaManutencaoPessoaView.java
 *
 * Created on 29/06/2011, 23:35:45
 */

package br.com.comprasPublicas.view.pesquisa;

import br.com.comprasPublicas.entity.Pessoa;
import br.com.comprasPublicas.util.HibernateUtil;
import br.com.comprasPublicas.view.cadastro.PessoaView;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author helsen
 */
public class PesquisaManutencaoPessoaView extends javax.swing.JDialog {

    /** Creates new form PesquisaManutencaoPessoaView */
    public PesquisaManutencaoPessoaView(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        preencher_tblFornecedores();
        lista = listar_fornecedores();
        preencher_fornecedores();
        tblFornecedores.setSelectionMode(0);

        //Método utilizado para centralizar o JFrame na tela
        Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((tela.width - this.getSize().width) / 2, (tela.height - this.getSize().height) / 2);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtCodigo = new javax.swing.JTextField();
        txtRazSocNome = new javax.swing.JFormattedTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtNomeFantasia = new javax.swing.JFormattedTextField();
        jLabel13 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblFornecedores = new javax.swing.JTable();
        btnSelecionar = new javax.swing.JButton();
        btnPesquisar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        txtCodigo.setName("txtCodigo"); // NOI18N

        txtRazSocNome.setName("txtRazSocNome"); // NOI18N
        txtRazSocNome.setNextFocusableComponent(txtNomeFantasia);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(br.com.comprasPublicas.compraspublicas.ComprasPublicasApp.class).getContext().getResourceMap(PesquisaManutencaoPessoaView.class);
        jLabel12.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N

        jLabel10.setFont(resourceMap.getFont("jLabel10.font")); // NOI18N
        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N

        jLabel11.setFont(resourceMap.getFont("jLabel11.font")); // NOI18N
        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        txtNomeFantasia.setName("txtNomeFantasia"); // NOI18N
        txtNomeFantasia.setNextFocusableComponent(btnPesquisar);

        jLabel13.setFont(resourceMap.getFont("jLabel13.font")); // NOI18N
        jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N
        jLabel13.setName("jLabel13"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblFornecedores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod Forn", "Razão Social / Nome", "Nome Fantasia", "CNPJ / CPF"
            }
        ));
        tblFornecedores.setName("tblFornecedores"); // NOI18N
        tblFornecedores.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jScrollPane1.setViewportView(tblFornecedores);

        btnSelecionar.setFont(resourceMap.getFont("btnSelecionar.font")); // NOI18N
        btnSelecionar.setMnemonic('s');
        btnSelecionar.setText(resourceMap.getString("btnSelecionar.text")); // NOI18N
        btnSelecionar.setName("btnSelecionar"); // NOI18N
        btnSelecionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelecionarActionPerformed(evt);
            }
        });

        btnPesquisar.setFont(resourceMap.getFont("btnPesquisar.font")); // NOI18N
        btnPesquisar.setMnemonic('p');
        btnPesquisar.setText(resourceMap.getString("btnPesquisar.text")); // NOI18N
        btnPesquisar.setName("btnPesquisar"); // NOI18N
        btnPesquisar.setNextFocusableComponent(tblFornecedores);
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 765, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel11)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtRazSocNome, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE))
                            .addComponent(jLabel12)
                            .addComponent(btnSelecionar, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel13)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNomeFantasia, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel12)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(txtRazSocNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnPesquisar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNomeFantasia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSelecionar)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSelecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarActionPerformed
        if (tblFornecedores.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(null, "Nenhum Fornecedor Selecionado");
        } else{
            String selecao = tblFornecedores.getModel().getValueAt(tblFornecedores.getSelectedRow(), 0).toString();
            PessoaView.pess = selecao;
            limpa_objetos();
            dispose();
        }
}//GEN-LAST:event_btnSelecionarActionPerformed

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
        lista = listar_parametros();
        preencher_fornecedores();
    }//GEN-LAST:event_btnPesquisarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PesquisaManutencaoPessoaView dialog = new PesquisaManutencaoPessoaView(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JButton btnSelecionar;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblFornecedores;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JFormattedTextField txtNomeFantasia;
    private javax.swing.JFormattedTextField txtRazSocNome;
    // End of variables declaration//GEN-END:variables

    private List lista;
    private Pessoa pessoa;



    private void preencher_tblFornecedores() {
        tblFornecedores.getColumnModel().getColumn(0).setPreferredWidth(20);
        tblFornecedores.getColumnModel().getColumn(1).setPreferredWidth(100);
        tblFornecedores.getColumnModel().getColumn(2).setPreferredWidth(100);
        tblFornecedores.getColumnModel().getColumn(3).setPreferredWidth(50);
    }

    private void preencher_fornecedores() {
        int tam_lista = lista.size();

        DefaultTableModel modelo_tbl = (DefaultTableModel) tblFornecedores.getModel();
        modelo_tbl.setNumRows(0);

        pessoa = new Pessoa();
        for (int i=0; i<tam_lista; i++ ){
            pessoa = (Pessoa) lista.get(i);
            modelo_tbl.addRow(new Object[]{pessoa.getId_pessoa(),
                                           pessoa.getNome_razao_soc(),
                                           pessoa.getNome_fantasia(),
                                           pessoa.getCpf_cnpj(),
                                          } );
        }
        lista = null;
    }

    private List listar_fornecedores() {
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        Criteria c = sessao.createCriteria(Pessoa.class);

        List listaBusca = c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

        transacao.commit();
        sessao.close();

        return listaBusca;
    }

    private List listar_parametros() {
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        Criteria c = sessao.createCriteria(Pessoa.class);
        c.addOrder(Order.asc("nome_razao_soc"));

        //Restrição pelo codigo Pessoa
        if (!txtCodigo.getText().equals("")) {
            int codigoBusca = Integer.parseInt(txtCodigo.getText());
            c.add(Restrictions.eq("id_pessoa", codigoBusca));
        }

        //Restrição pela Razao Social (Juridica) ou Nome (Fisica)
        if (!txtRazSocNome.getText().equals("")){
            String razSocialBusca = txtRazSocNome.getText();
            c.add(Restrictions.ilike("nome_razao_soc", razSocialBusca, MatchMode.ANYWHERE));
        }

        //Restrição pelo Nome Fantasia
        if (!txtNomeFantasia.getText().equals("")){
            String nomeFantasiaBusca = txtNomeFantasia.getText();
            c.add(Restrictions.ilike("nome_fantasia", nomeFantasiaBusca, MatchMode.ANYWHERE));
        }

        List listaBusca = c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

        transacao.commit();
        sessao.close();
        return listaBusca;
    }

    private void limpa_objetos() {
        pessoa = null;
        lista = null;
    }

}
